/**
 * 财务报表控制器 - 处理财务文档上传、AI分析等REST API接口
 *
 * 开发人员：徐少洋
 * 开发时间：2025-11-08 至 2025-11-12
 * 模块职责：提供财务报表相关的REST API接口，支持文档上传、AI分析、结果保存等完整报表处理功能
 *
 * 技术要点：
 * - RESTful API设计，遵循REST规范
 * - 多租户架构，企业级数据隔离
 * - 财务文档上传和存储管理
 * - AI分析集成和异步处理机制
 * - 报表状态管理和异常处理机制
 *
 * 开发故事：负责财务报表控制器的开发，与报表服务层和AI分析服务深度配合，为企业提供专业的财务文档智能分析服务。
 */
package com.pbl.controller;

import com.pbl.ai.AiClient;
import com.pbl.common.model.ApiResponse;
import com.pbl.entity.FinanceReport;
import com.pbl.repository.FinanceReportRepository;
import com.pbl.service.ReportService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/enterprises/{enterpriseId}/reports")
public class ReportController {

    private final ReportService reportService;
    private final FinanceReportRepository financeReportRepository;
    private final AiClient aiClient;

    /**
     * 构造财务报表控制器
     * @param reportService 报表服务层
     * @param financeReportRepository 报表数据访问层
     * @param aiClient AI客户端
     */
    public ReportController(ReportService reportService, FinanceReportRepository financeReportRepository, AiClient aiClient) {
        this.reportService = reportService;
        this.financeReportRepository = financeReportRepository;
        this.aiClient = aiClient;
    }

    @PostMapping
    public ApiResponse<FinanceReport> create(@PathVariable Long enterpriseId,
                                             @RequestParam Long userId,
                                             @RequestParam String fileName,
                                             @RequestParam String fileType,
                                             @RequestParam int fileSize,
                                             @RequestParam String storageUrl) {
        return ApiResponse.success(reportService.createUpload(enterpriseId, userId, fileName, fileType, fileSize, storageUrl));
    }

    @GetMapping
    public ApiResponse<List<FinanceReport>> list(@PathVariable Long enterpriseId) {
        return ApiResponse.success(financeReportRepository.findByEnterprise_IdOrderByCreatedAtDesc(enterpriseId));
    }

    @PostMapping("/{id}/analyze")
    public ApiResponse<FinanceReport> analyze(@PathVariable Long enterpriseId, @PathVariable Long id,
                                              @RequestParam String prompt) {
        FinanceReport fr = reportService.markAnalyzing(id);
        String result = aiClient.analyzeImage(fr.getStorageUrl(), prompt);
        return ApiResponse.success(reportService.saveAnalysis(id, result == null ? "" : result, result != null));
    }
}
